package com.tfleo.mealssenger;

import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.adapter.CommentListAdapter;
import com.tfleo.mealssenger.adapter.FriendCheckBoxAdapter;
import com.tfleo.mealssenger.object.Comment;
import com.tfleo.mealssenger.object.Food;
import com.tfleo.mealssenger.object.FriendSelection;
import com.tfleo.mealssenger.utility.DataFetcher;

import com.github.ignition.core.widgets.RemoteImageView;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Activity to show details of Food object, including
 * comments made by user and number of likes.
 * 
 * User can add comment and like to the particular Food
 * in this activity.
 * 
 * @author Theodore Felix Leo
 *
 */
public class FoodActivity extends Activity {
	private static final long FIVE_HOUR = 5*3600*1000;
	
	private ListView vCommentList;
	private ListView vFriendList;
	private RemoteImageView vFoodImage;
	private TextView vFoodName;
	private TextView vFoodLocation;
	private TextView vFoodDescription;
	private TextView vNumMealup;
	private RatingBar vRating;
	private Button vMealupButton;
	private Button vWantButton;
	private Button vAddCommentButton;
	private Button vShareButton;
	
	private Context mContext;
	private LayoutInflater mInflater;
	
	private String mFoodName;
	private String mFoodLocationName;
	private String mFoodDescription;
	private String mFoodImageUrl;
	private String mFoodCategory;
	private int mFoodId;
	private int mFoodLocationId;
	private int mFoodNumMealup;
	private int mUserId;
	private float mCommentRating = 0;
	private float mFoodRating = 0;
	
	private ArrayList<Comment> mCommentList;
	private CommentListAdapter mCommentAdapter; 
	private FriendCheckBoxAdapter mFriendAdapter;
	
	private SharedPreferences mAppSettings;
	private SharedPreferences.Editor mPrefEditor;
	
	private String mAuth;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.food_layout);
		mContext = this;
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mAuth = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); //for authentication
		mAppSettings = getSharedPreferences(Main.USER_DATA, MODE_PRIVATE);
		mPrefEditor = mAppSettings.edit();
		mUserId = mAppSettings.getInt(Main.USER_ID, 0);
		if(mUserId == 0) {
			Toast.makeText(mContext, "Error: Invalid user!", Toast.LENGTH_SHORT);
			finish();
		}
		
		Bundle extras = getIntent().getExtras();
        if(extras != null) {
        	mFoodId = extras.getInt("id", 0);
        	mFoodName = extras.getString("name");
        	mFoodLocationId = extras.getInt("location_id", 0);
        	mFoodLocationName = extras.getString("location_name");
        	mFoodDescription = extras.getString("description");
        	mFoodCategory = extras.getString("category");
        	mFoodImageUrl = extras.getString("image");
        	mFoodNumMealup = extras.getInt("likes", -1);
        	mFoodRating = extras.getFloat("rating", -1);
        	
        	if(extras.getBoolean("ack", false)) {
        		AcknowledgeShareTask task = new AcknowledgeShareTask();
        		task.execute(mUserId, mFoodId);
        	}
        } else {
        	Toast.makeText(mContext, "Error: Bundle is null!", Toast.LENGTH_SHORT);
        	finish();
        }
        
        if(mFoodId == 0) {
        	Toast.makeText(mContext, "Error: No food referred!", Toast.LENGTH_SHORT);
        	finish();
        }
        
        if(mFoodName == null || mFoodLocationId == 0 || mFoodLocationName == null || mFoodRating == -1
        		|| mFoodDescription == null || mFoodImageUrl == null || mFoodNumMealup == -1) {
        	FetchFoodTask foodTask = new FetchFoodTask();
        	foodTask.execute(mFoodId);
        } else {
        	vFoodName = (TextView) findViewById(R.id.food_name);
            vFoodName.setText(mFoodName);
            
            vFoodLocation = (TextView) findViewById(R.id.food_loc);
            vFoodLocation.setText(mFoodLocationName);
            
            vFoodDescription = (TextView) findViewById(R.id.food_description);
            vFoodDescription.setText(mFoodDescription);
            
            vFoodImage = (RemoteImageView) findViewById(R.id.food_img);
            vFoodImage.setImageUrl(mFoodImageUrl);
            vFoodImage.loadImage();
            
            vNumMealup = (TextView) findViewById(R.id.num_mealup);
            vNumMealup.setVisibility(View.VISIBLE);
            vNumMealup.setText(Integer.toString(mFoodNumMealup) + " meal-up");
            
            vRating = (RatingBar) findViewById(R.id.rating);
            vRating.setRating(mFoodRating);
        }
	
        
        vCommentList = (ListView) findViewById(R.id.comment_list);
        
        FetchCommentTask commentTask = new FetchCommentTask();
        commentTask.execute(mFoodId);
        
        vMealupButton = (Button) findViewById(R.id.mealup_btn);
        vMealupButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AddMealupTask task = new AddMealupTask();
				task.execute();
				
			}
        });
        
        vWantButton = (Button) findViewById(R.id.want_btn);
        vWantButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(addWant()){
					vWantButton.setText("Wanted");
					vWantButton.setEnabled(false);
					vWantButton.setBackgroundColor(Color.parseColor("#00000000"));
					vWantButton.setTextColor(getResources().getColor(R.color.tan));
				} else {
					Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
				}
				
			}
        });
        
        VerifyMealedAndWantedTask mealedAndWantedTask = new VerifyMealedAndWantedTask();
        mealedAndWantedTask.execute(mAppSettings.getInt(Main.LAST_MEALUP_ID, 0), mFoodId, 
        		mAppSettings.getInt(Main.USER_ID, 0));
        
        vShareButton = (Button) findViewById(R.id.share_btn);
        vShareButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		 buildShareDialog();	
			}
        });
        
        vAddCommentButton = (Button) findViewById(R.id.add_comment_btn);
        
        vAddCommentButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				 buildCommentDialog();	
			}
        });
        
        vCommentList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//TODO
			}
		});
        
	}
	
	@Override
	public void onResume() {
		super.onResume();
//		mFoodLikes = DataFetcher.fetchLikes(mFoodId);
//		mComments = DataFetcher.fetchFoodComment(mFoodId);
//		mCommentAdapter.notifyDataSetChanged();
	}

	private boolean addMealup() {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "food/" + mFoodId + "/mealup");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(mUserId)));
			//nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(mFoodId)));
			nameValuePairs.add(new BasicNameValuePair("food_name", mFoodName));
			nameValuePairs.add(new BasicNameValuePair("category", mFoodCategory));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String body = httpclient.execute(httppost, responseHandler);
			JSONObject jo = new JSONObject(body);
			int lastInsertId;
			if((lastInsertId = jo.getInt("code")) > 0) {
				mPrefEditor.putInt(Main.LAST_MEALUP_ID, lastInsertId);
				mPrefEditor.commit();
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	private boolean addWant() {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "food/" + mFoodId + "/wanted");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(mUserId)));
			//nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(mFoodId)));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			
			if(response.getInt("code") > 0) {
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	private boolean addComment(int userId, String userName, int foodId, float rating, String content) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "food/" + mFoodId + "/postcomment");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("user_id", Integer.toString(userId)));
			nameValuePairs.add(new BasicNameValuePair("user_name", userName));
			//nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(foodId)));
			nameValuePairs.add(new BasicNameValuePair("rating", Float.toString(rating)));
			nameValuePairs.add(new BasicNameValuePair("comment", content));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String body = httpclient.execute(httppost, responseHandler);
			JSONObject jo = new JSONObject(body);
			if((jo.getInt("code")) > 0) {
				mCommentList = DataFetcher.fetchFoodComment(foodId);
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	private boolean addShare(HashMap<Integer, Boolean> friendSelected) {
		StringBuilder friendId = new StringBuilder();
		for (Map.Entry<Integer, Boolean> entry : friendSelected.entrySet()) {
			if(entry.getValue()) {
				friendId.append(entry.getKey()).append(",");
			}
		}
		if(friendId.length() > 0) {
			friendId.deleteCharAt(friendId.length()-1);
		}
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "food/" + mFoodId + "/share");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("from_user", Integer.toString(mUserId)));
			nameValuePairs.add(new BasicNameValuePair("to_user", friendId.toString()));
			//nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(mFoodId)));
			nameValuePairs.add(new BasicNameValuePair("food_name", mFoodName));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			if(response.getInt("code") > 0) {
				return true;
			} else {
				Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	private void buildCommentDialog() {
		View layout = mInflater.inflate(R.layout.add_comment, null);
	    final EditText vContent = (EditText) layout.findViewById(R.id.comment_content);
	    final RatingBar ratingbar = (RatingBar) layout.findViewById(R.id.rating);
	    ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
	        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
	            mCommentRating = rating;
	        }
	    });
	    
	    //Building dialog
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setView(layout);
	    
	    builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        	String content;
	        	if((content = vContent.getText().toString().trim()).equals("")) {
	        		Toast.makeText(mContext, "Error: Empty comment!", Toast.LENGTH_SHORT).show();
	        		return;
	        	}
	        	AddCommentTask addCommentTask = new AddCommentTask();
	            String[] data = new String[]{
	            		String.valueOf(mAppSettings.getInt(Main.USER_ID, 0)),
	            		mAppSettings.getString(Main.USER_NAME, ""),
	            		String.valueOf(mFoodId),
	            		String.valueOf(mCommentRating),
	            		content
	            };
	            addCommentTask.execute(data);  
	        }
	    });
	    
	    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	            dialog.dismiss();
	        }
	    });
	    
	    AlertDialog dialog = builder.create();
		dialog.setTitle("Add comment");
		dialog.show();
		
		ViewGroup parent = (ViewGroup)layout.getParent();
		parent.setPadding(0, 0, 0, 1);
	}
	
	private void buildShareDialog() {
		View layout = mInflater.inflate(R.layout.add_share, null);
		
	    vFriendList = (ListView) layout.findViewById(R.id.friend_list);
//	    ArrayList<FriendSelection> friends = new ArrayList<FriendSelection>();
//	    friends = DataFetcher.fetchFriends(mUserId);
//        final FriendCheckBoxAdapter adapter = new FriendCheckBoxAdapter(mContext, 
//        		R.layout.add_share_list_entry, R.id.name, friends, mInflater);
//        vFriendList.setAdapter(adapter);
	    
	    FetchFriendListTask friendTask = new FetchFriendListTask();
	    friendTask.execute(mUserId);
	    
	    //Building dialog
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setView(layout);
	    
	    builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
	        @SuppressWarnings("unchecked")
			public void onClick(DialogInterface dialog, int which) {
	        	AddShareTask addShareTask = new AddShareTask();
	        	addShareTask.execute(mFriendAdapter.getSelected());
	        }
	    });
	    
	    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	            dialog.dismiss();
	        }
	    });
	    
	    AlertDialog dialog = builder.create();
		dialog.setTitle("Share with...");
		dialog.show();
		
		ViewGroup parent = (ViewGroup)layout.getParent();
		parent.setPadding(0, 0, 0, 1);
	}
	
	private boolean isLastMealedFood(int mealupId, int foodId, int userId) {
		if(mealupId == 0) {
			return false;
		}
		try {
			URL url = new URL(Main.SERVER_URL + "mealup/" + mealupId);
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
			String body;
			while ((body = in.readLine()) != null) {
				JSONObject jo = new JSONObject(body);
				
				if(jo.getInt("code") == 1) {
					JSONObject response = jo.getJSONObject("response");
					boolean recent = true;
					
					String fullDateTime = response.getString("date");
					String[] splitDateTime = fullDateTime.split(" ");
					
					String[] splitDate = splitDateTime[0].split("-");
					String[] splitTime = splitDateTime[1].split(":");
					
					//mFoodNumMealup = response.getInt("num_mealup");
					
					int year = Integer.parseInt(splitDate[0]);
					int month = Integer.parseInt(splitDate[1]);
					int day = Integer.parseInt(splitDate[2]);
					int hour = Integer.parseInt(splitTime[0]);
					int minute = Integer.parseInt(splitTime[1]);
					
					Calendar c = Calendar.getInstance();
					GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, minute);
					
					if(c.getTimeInMillis() - gc.getTimeInMillis() > FIVE_HOUR) {
						recent = false;
					}

					if(recent && (foodId == response.getInt("food_id")) && 
							(userId == response.getInt("user_id"))) {
						return true;
					} else {
						return false;
					}
				}
			}
		} catch(MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	private boolean isWanted(int foodId, int userId) {
		try {
			URL url = new URL(Main.SERVER_URL + "is_wanted.php?user_id=" + userId + "&food_id=" + foodId);
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
			String responseBody;
			while ((responseBody = in.readLine()) != null) {
				JSONObject response = new JSONObject(responseBody);
				
				if(response.getInt("code") == 1) {
					return true;
				} else {
					return false;
				}
			}
			
		} catch(MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	private class FetchFoodTask extends AsyncTask<Integer, Void, Food> {	
		@Override
		protected Food doInBackground(Integer... id) {
			int foodId = id[0];
			
			return DataFetcher.fetchFood(foodId);	
		}
		
		@Override
		protected void onPostExecute(Food result) {
			if(result != null) {
				mFoodName = result.name;
				mFoodLocationId = result.locationId;
	        	mFoodLocationName = result.locationName;
	        	mFoodDescription = result.description;
	        	mFoodImageUrl = result.imageUrl;
	        	mFoodCategory = result.category;
	        	mFoodNumMealup = result.numEaten;
	        	mFoodRating = result.rating;
	        	
	        	//Setup views
	        	vFoodName = (TextView) findViewById(R.id.food_name);
	            vFoodName.setText(mFoodName);
	            
	            vFoodLocation = (TextView) findViewById(R.id.food_loc);
	            vFoodLocation.setText(mFoodLocationName);
	            
	            vFoodDescription = (TextView) findViewById(R.id.food_description);
	            vFoodDescription.setText(mFoodDescription);
	            
	            vFoodImage = (RemoteImageView) findViewById(R.id.food_img);
	            vFoodImage.setImageUrl(mFoodImageUrl);
	            vFoodImage.loadImage();
	            
	            vNumMealup = (TextView) findViewById(R.id.num_mealup);
	            vNumMealup.setText(Integer.toString(mFoodNumMealup) + " meal-up");
	            vNumMealup.setVisibility(View.VISIBLE);
	            
	            
	            vRating = (RatingBar) findViewById(R.id.rating);
	            vRating.setRating(mFoodRating);
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    		}
	    }
	}
	
	private class FetchCommentTask extends AsyncTask<Integer, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Loading...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(Integer... id) {
			int foodId = id[0];
			
			mCommentList = DataFetcher.fetchFoodComment(foodId);
			if(mCommentList == null) {
				return false;
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mCommentAdapter = new CommentListAdapter(mContext, R.layout.comment_list_entry, 
						R.id.name, mCommentList, mInflater);
                vCommentList.setAdapter(mCommentAdapter);
        		
				mProgressDialog.dismiss();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    			mProgressDialog.dismiss();
    		}
	    }	
	}
	
	private class AddMealupTask extends AsyncTask<Void, Void, Boolean> {		
		@Override
		protected Boolean doInBackground(Void... v) {
			return addMealup();
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mFoodNumMealup += 1;
				vNumMealup.setText(Integer.toString(mFoodNumMealup) + " meal-up");
				vMealupButton.setText("Mealed");
				vMealupButton.setEnabled(false);
				vMealupButton.setBackgroundColor(Color.parseColor("#00000000"));
				vMealupButton.setTextColor(getResources().getColor(R.color.tan));
			} else {
				Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT).show();
			}
	    }	
	}
	
	private class FetchFriendListTask extends AsyncTask<Integer, Void, ArrayList<FriendSelection>> {
		@Override
		protected ArrayList<FriendSelection> doInBackground(Integer... id) {
			return DataFetcher.fetchFriendSelection(id[0], id[0], mAuth);
		}
		
		@Override
		protected void onPostExecute(ArrayList<FriendSelection> result) {
			mFriendAdapter = new FriendCheckBoxAdapter(mContext, 
	        		R.layout.add_share_list_entry, R.id.name, result, mInflater);
	        vFriendList.setAdapter(mFriendAdapter);
	    }
	}
	
	private class AcknowledgeShareTask extends AsyncTask<Integer, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... id) {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Main.SERVER_URL + "ack_share.php");

			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				nameValuePairs.add(new BasicNameValuePair("to_user", Integer.toString(id[0])));
				nameValuePairs.add(new BasicNameValuePair("food_id", Integer.toString(id[1])));
				nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String responseBody = httpclient.execute(httppost, responseHandler);
				JSONObject response = new JSONObject(responseBody);
				if(response.getInt("code") > 0) {
					return true;
				} else {
					return false;
				}
			} catch(Exception e){
				e.printStackTrace();
			}
			
			return false;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(!result) {
				Toast.makeText(mContext, "Error: Something wrong when acknowledging share", 
						Toast.LENGTH_SHORT).show();
			}
	    }
	}
	
	private class VerifyMealedAndWantedTask extends AsyncTask<Integer, Void, Integer> {
		@Override
		protected Integer doInBackground(Integer... id) {
			int eatId = id[0];
			int foodId = id[1];
			int userId = id[2];
			
			boolean isLast = isLastMealedFood(eatId, foodId, userId);
			boolean isWanted = isWanted(foodId, userId);
			
			if(isLast && isWanted) {
				return 1;
			} else if(isLast && !isWanted) {
				return 2;
			} else if(!isLast && isWanted) {
				return 3;
			} else {
				return 4;
			}
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			switch(result) {
			case 1:
				vMealupButton.setText("Mealed!");
				vMealupButton.setEnabled(false);
				vMealupButton.setBackgroundColor(Color.parseColor("#00000000"));
				vMealupButton.setTextColor(getResources().getColor(R.color.tan));
				
				vWantButton.setText("Wanted!");
				vWantButton.setEnabled(false);
				vWantButton.setBackgroundColor(Color.parseColor("#00000000"));
				vWantButton.setTextColor(getResources().getColor(R.color.tan));
				break;
			case 2:
				vMealupButton.setText("Mealed!");
				vMealupButton.setEnabled(false);
				vMealupButton.setBackgroundColor(Color.parseColor("#00000000"));
				vMealupButton.setTextColor(getResources().getColor(R.color.tan));
				break;
			case 3:
				vWantButton.setText("Wanted!");
				vWantButton.setEnabled(false);
				vWantButton.setBackgroundColor(Color.parseColor("#00000000"));
				vWantButton.setTextColor(getResources().getColor(R.color.tan));
				break;
			}
			vMealupButton.setVisibility(View.VISIBLE);
			vWantButton.setVisibility(View.VISIBLE);
			vNumMealup.setText(Integer.toString(mFoodNumMealup) + " meal-up");
	    }
	}
	
	private class AddCommentTask extends AsyncTask<String, Void, Boolean> {
		@Override
		protected Boolean doInBackground(String... data) {
			int userId = Integer.valueOf(data[0]);
			String userName = data[1];
			int foodId = Integer.valueOf(data[2]);
			float rating = Float.valueOf(data[3]);
			String content = data[4];
			
			return addComment(userId, userName, foodId, rating, content);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mCommentAdapter = new CommentListAdapter(mContext, R.layout.comment_list_entry, 
						R.id.name, mCommentList, mInflater);
				vCommentList.setAdapter(mCommentAdapter);
    		} else {
    			Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
    		}
	    }	
	}
	
	private class AddShareTask extends AsyncTask<HashMap<Integer, Boolean>, Void, Boolean> {
		@Override
		protected Boolean doInBackground(HashMap<Integer, Boolean>... data) {
			return addShare(data[0]);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				Toast.makeText(mContext, "You've shared this food!", Toast.LENGTH_SHORT);
    		} else {
    			Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT);
    		}
	    }	
	}
}
